<template>
  <div>
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item v-bind:to='{ path: "/" }'>首页</el-breadcrumb-item>
      <el-breadcrumb-item>移动端管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class='dict-main'>
      <el-tabs v-model='activeName' class='title-top'>
        <el-tab-pane label='用户管理' name='first'>
          <div class='main-module charger'>
            <el-row class='posre'>
              <el-col :span='12' class='text-right search-top'>
                <el-button size='small' type='success' icon='el-icon-plus' @click='openAppUserAddWin()'>创建平台用户</el-button>
                <el-button size='small' icon='el-icon-arrow-up' @click='show = !show' plain v-if='show==true'>搜索
                </el-button>
                <el-button size='small' icon='el-icon-arrow-down' @click='show = !show' plain v-else >搜索</el-button>

              </el-col>
            </el-row>
            <el-collapse-transition>
              <div v-show='show'>
                <el-row :gutter='20' class='bill-search'>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='bill-search-title fl'>注册手机</label>
                    <el-input placeholder="手机号码查询" v-model='params.mobile'></el-input>
                  </el-col>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='bill-search-title fl'>用户昵称</label>
                    <el-input placeholder="用户昵称查询" v-model='params.nickName'></el-input>
                  </el-col>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='demonstration bill-search-title fl'>注册日期</label>
                    <div class='block'>
                      <el-date-picker
                        v-model='startDates'
                        value-format='yyyy-MM-dd'
                        type='daterange'
                        align='right'
                        unlink-panels
                        range-separator='至'
                        start-placeholder='开始日期'
                        end-placeholder='结束日期'
                        :picker-options='pickerOptions'>
                      </el-date-picker>
                    </div>
                  </el-col>
                  <el-col :span='14' class='bill-search-row text-right'>
                    <el-button type='warning' size='small' icon='el-icon-search' @click='clearParams()'>清空</el-button>
                    <el-button type='primary' size='small' icon='el-icon-search' @click='searchAppUserData()'>检索</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-transition>
            <!--表格-->
            <template>
              <el-table ref="appUserTable" :data='appUserDatas' stripe tooltip-effect='dark' style='width: 100%'
                        @sort-change="createTimeSort" @filter-change="filterHandler">
                <el-table-column label='注册时间' prop='createTime' align='center' min-width="150"
                                 sortable="custom"></el-table-column>
                <el-table-column label='用户类型' prop='showUserType' columnKey="userType" min-width="150" show-overflow-tooltip
                                 align='center' :filters="userTypeFilter" :filter-multiple=false>
                  <!--<template slot-scope="scope">
                    <span v-if="scope.row.userType==1" >普通用户</span>
                    <span v-if="scope.row.userType==0" style="color: #1784ff">平台用户</span>
                  </template>-->
                </el-table-column>
                <el-table-column label='注册手机' prop='mobile' min-width="120" align='center'></el-table-column>
                <el-table-column label='昵称' prop="nickName" min-width="130" align='center'></el-table-column>
                <el-table-column label='性别' prop="showSex" min-width="130" align='center'></el-table-column>
                <el-table-column label='积分' prop="score" min-width="130" align='center'></el-table-column>
                <el-table-column label='状态' prop='status' columnKey="status" min-width="150" show-overflow-tooltip
                                 align='center' :filters="statusFilter" :filter-multiple=false>
                  <template slot-scope="scope">
                    <span v-if="scope.row.status==1" style="color: #1784ff">正常</span>
                    <span v-if="scope.row.status==0" style="color: red">锁定</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="240" align="left">
                  <template slot-scope="scope">
                    <el-button size="mini" type="success" plain @click="appUserDetail(scope.row.userId)">详情</el-button>
                    <el-button size="mini" type="warning" plain v-if="scope.row.status==1"
                               @click='modifyStatus(scope.row.userId,0)'>锁定
                    </el-button>
                    <el-button size="mini" type="success" plain v-if="scope.row.status==0"
                               @click='modifyStatus(scope.row.userId,1)'>解锁
                    </el-button>
                    <el-dropdown class='m-left10' v-if="scope.row.userType==0">
                      <el-button type='primary' size='mini'>
                        更多<i class='el-icon-arrow-down el-icon--right'></i>
                      </el-button>
                      <el-dropdown-menu slot='dropdown'>
                        <el-button size="mini"  type="primary" plain @click="openAppUserEditWin(scope.row.userId)">修改</el-button>
                        <el-button size="mini"  type="primary" plain @click="openResetPasswordWin(scope.row.userId)">重置密码</el-button>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </template>
            <!--分页-->
            <div class='block text-center'>
              <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange'
                             :current-page='pageable.currentPage' :page-sizes='[20, 40, 80, 100]'
                             :page-size='pageable.pageSize' layout='total, sizes, prev, pager, next, jumper'
                             :total='pageable.total'></el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <!--用户详情-->
        <div>
          <el-dialog title='用户详情' width="600px" :visible.sync='dialogViewVisible'  >
            <el-form label-width='120px'>
              <el-form-item label='注册手机:'>
                <span>{{appUserInfo.mobile}}</span> （<span>{{appUserInfo.showUserType}}</span>）
              </el-form-item>
              <el-form-item label='昵称:'>
                <span>{{appUserInfo.nickName}}</span>
              </el-form-item>
              <el-form-item label='注册时间:'>
                <span>{{appUserInfo.createTime}}</span>
              </el-form-item>
              <el-form-item label='性别:'>
                <span>{{appUserInfo.showSex}}</span>
              </el-form-item>
              <el-form-item label='状态:'>
                <span>{{appUserInfo.showStatus}}</span>
              </el-form-item>
              <el-form-item label='积分:'>
                <span>{{appUserInfo.score}}</span>
              </el-form-item>
              <el-form-item label='头像:'>
                <span><img :src="appUserInfo.fullHeadImg" width="100px;" height="100px;"/></span>
              </el-form-item>
              <el-form-item label='个性签名:'>
                <p>{{appUserInfo.signature}}</p>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button type='primary' @click='dialogViewVisible=false'>关闭</el-button>
            </div>
          </el-dialog>
        </div>

        <!--添加平台用户-->
        <div>
          <el-dialog title='添加平台用户' width="600px" :visible.sync='dialogAddVisible'  >
            <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" label-suffix=":">
              <el-form-item label='用户类型' >
                <span style="color:#20a0ff;font-size: 16px;">平台用户</span>
              </el-form-item>
              <el-form-item label='注册手机' prop='mobile'>
                <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
              <el-form-item label='登录密码' prop='password'>
                <el-input type="password" v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label='昵称' prop='nickName'>
                <el-input v-model="addForm.nickName"></el-input>
              </el-form-item>
              <el-form-item label='头像' prop='headImg' >
                <el-upload
                  class='avatar-uploader'
                  action=''
                  :show-file-list='false'
                  :http-request='doUploadHeadImg'
                  :before-upload='beforeAvatarUpload'>
                  <img v-if='addForm.headImg' :v-model='addForm.headImg' :src='addForm.fullHeadImg' class='avatar' >
                  <i v-else class='el-icon-plus avatar-uploader-icon'>用户头像</i>
                </el-upload>
              </el-form-item>
              <el-form-item label='个性签名' prop='signature'>
                <el-input type="textarea" v-model="addForm.signature"></el-input>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='dialogAddVisible=false'>取消</el-button>
              <el-button type='primary' @click='submitAddForm'>保存</el-button>
            </div>
          </el-dialog>
        </div>

        <!--修改平台用户-->
        <div>
          <el-dialog title='修改平台用户' width="600px" :visible.sync='dialogEditVisible'  >
            <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" label-suffix=":">
              <el-form-item label='用户类型' >
                <span style="color:#20a0ff;font-size: 16px;">平台用户</span>
              </el-form-item>
              <el-form-item label='注册手机' prop='mobile'>
                <el-input v-model="editForm.mobile"></el-input>
              </el-form-item>
              <el-form-item label='昵称' prop='nickName'>
                <el-input v-model="editForm.nickName"></el-input>
              </el-form-item>
              <el-form-item label='头像' prop='headImg' >
                <el-upload
                  class='avatar-uploader'
                  action=''
                  :show-file-list='false'
                  :http-request='doEditHeadImg'
                  :before-upload='beforeAvatarUpload'>
                  <img v-if='editForm.headImg' :v-model='editForm.headImg' :src='editForm.fullHeadImg' class='avatar' >
                  <i v-else class='el-icon-plus avatar-uploader-icon'>用户头像</i>
                </el-upload>
              </el-form-item>
              <el-form-item label='个性签名' prop='signature'>
                <el-input type="textarea" v-model="editForm.signature"></el-input>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='dialogEditVisible=false'>取消</el-button>
              <el-button type='primary' @click='submitEditForm'>保存</el-button>
            </div>
          </el-dialog>
        </div>

        <!--平台用户重置密码-->
        <div>
          <el-dialog title='重置密码' width="600px" :visible.sync='dialogPasswordVisible'  >
            <el-form :model="resetPasswordForm" :rules="rules" ref="resetPasswordForm" label-width="100px" label-suffix=":">
              <el-form-item label='新密码' prop='password'>
                <el-input type="password" v-model="resetPasswordForm.password"></el-input>
              </el-form-item>
              <el-form-item label='确认密码' prop='confirmPassword'>
                <el-input type="password" v-model="resetPasswordForm.confirmPassword"></el-input>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='dialogPasswordVisible=false'>取消</el-button>
              <el-button type='primary' @click='resetPassword'>确认</el-button>
            </div>
          </el-dialog>
        </div>

      </el-tabs>
    </div>
  </div>
</template>
<script>
  import {
    loadAppUserDatas,
    addAppUser,
    editAppUser,
    resetUserPassword,
    loadAppUserDetail,
    modifyStatus
  } from '@/api/app-user';
  import { uploadOss } from '@/api/image-oss';
  import { getOSSProperties } from '@/api/image';

  export default {
    data() {
      var validateConfirmPassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'));
        } else if (value !== this.resetPasswordForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        ossProperties: {},
        baseDir: 'steach/app-user',
        dialogViewVisible: false,
        dialogAddVisible: false,
        dialogEditVisible: false,
        dialogPasswordVisible: false,
        show: false,
        pageable: {
          currentPage: 1,
          pageSize: 20
        },
        activeName: 'first',
        appUserDatas: [], //列表数据
        appUserInfo: '',//app用户详情
        startDates: '',
        userTypeFilter: [
          {
            text: '普通用户', value: '1'
          },
          {
            text: '平台用户', value: '0'
          }],
        statusFilter: [
          {
            text: '正常', value: '1'
          },
          {
            text: '锁定', value: '0'
          }],
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        },
        params: {
          page: 1,
          size: 20,
          userType: '',
          mobile: '',
          nickName: '',
          status: '',
          startDate: '',
          endDate: '',
          createTimeSort: ''
        },
        addForm: {
          mobile: '',
          password: '',
          nickName: '',
          headImg: '',
          signature: ''
        },
        editForm: {
          userId: '',
          mobile: '',
          nickName: '',
          headImg: '',
          signature: ''
        },
        resetPasswordForm: {
          userId: '',
          password: '',
          confirmPassword: ''
        },
        rules: {
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {min: 11, max: 11, message: '请输入11位正确的手机号码', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入登录密码', trigger: 'blur'},
            {min: 6, max: 8, message: '请输入6-18位登录密码', trigger: 'blur'}
          ],
          confirmPassword: [
            {required: true, validator: validateConfirmPassword, trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: '请输入昵称', trigger: 'blur'},
            {min: 2, max: 20, message: '请输入2-20位昵称', trigger: 'blur'}
          ],
          headImg: [
            {required: true, message: '请上传平台用户头像信息', trigger: 'blur'}
          ]
        }
      };
    },
    filters: {},
    methods: {
      //获取数据
      loadAppUserDatas() {
        this.params.page = this.pageable.currentPage;
        this.params.size = this.pageable.pageSize;
        if (this.startDates != null) {
          this.params.startDate = this.startDates[0];
          this.params.endDate = this.startDates[1];
        }
        loadAppUserDatas(this.params).then(response => {
          if (response.code !== 0) {
            this.$message({
              message: response.message,
              type: 'error'
            });
          } else {
            this.appUserDatas = response.data.data;
            this.pageable = {
              currentPage: response.data.pageInfo.page,
              pageSize: response.data.pageInfo.pageSize,
              total: response.data.pageInfo.total
            };
          }
        });
      },
      //搜索
      searchAppUserData() {
        this.loadAppUserDatas();
      },
      clearParams() {
        this.params = {};
        this.startDates = [];
      },
      //创建时间排序
      createTimeSort(params) {
        if (params.prop == 'createTime') {
          if (params.order == 'ascending') {
            this.params.createTimeSort = 1;
          } else if (params.order == 'descending') {
            this.params.createTimeSort = 2;
          }
        }
        this.loadAppUserDatas();
      },
      //状态筛选 用户类型筛选
      filterHandler(filter) {
        if(filter.userType!=null && this.params.userType != filter.userType[0]){
          this.params.userType = filter.userType[0];
        }
        if(filter.status!=null && this.params.status != filter.status[0]){
          this.params.status = filter.status[0];
        }
        this.loadAppUserDatas();
      },
      openAppUserAddWin(){
        this.dialogAddVisible = true;
        this.addForm= {
          mobile: '',
          password: '',
          nickName: '',
          headImg: '',
          signature: ''
        }
      },
      openAppUserEditWin(userId){
        loadAppUserDetail(userId).then(response => {
          if (response.code !== 0) {
            this.$message({
              message: response.message,
              type: 'error'
            });
          } else {
            this.dialogEditVisible=true;
            this.editForm= {
              userId: response.data.userId,
              mobile: response.data.mobile,
              nickName: response.data.nickName,
              headImg: response.data.headImg,
              fullHeadImg: response.data.fullHeadImg,
              signature: response.data.signature
            }
          }
        });
      },
      openResetPasswordWin(userId) {
        this.dialogPasswordVisible= true;
        this.resetPasswordForm= {
          userId: userId,
          password: '',
          confirmPassword: ''
        }
      },
      appUserDetail(userId){
        loadAppUserDetail(userId).then(response => {
          if (response.code !== 0) {
            this.$message({
              message: response.message,
              type: 'error'
            });
          } else {
            this.dialogViewVisible=true;
            this.appUserInfo = response.data;
          }
        });
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传logo图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传logo图片大小不能超过 10MB!');
        }
        return isJPG && isLt2M;
      },
      doUploadHeadImg (file) {
        var _this = this;
        uploadOss(_this.ossProperties, file, function (url) {
          _this.addForm.headImg=url;
          _this.addForm.fullHeadImg=_this.ossProperties.showUrl+url;
        });
      },
      doEditHeadImg (file) {
        var _this = this;
        uploadOss(_this.ossProperties, file, function (url) {
          _this.editForm.headImg=url;
          _this.editForm.fullHeadImg=_this.ossProperties.showUrl+url;
        });
      },
      modifyStatus(userId,status){
        var that = this;
        this.$confirm('确定要'+(status==0?'锁定':'解锁')+'该用户吗，是否继续操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          modifyStatus(userId,status).then(response => {
            if (response.code == 0) {
              that.$message({
                message: (status==0?'锁定':'解锁')+'成功',
                type: 'success'
              });
              that.loadAppUserDatas();
            } else {
              that.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        });
      },
      submitAddForm() {
        var that = this;
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            addAppUser(that.addForm).then(response => {
              if (response.code == 0) {
                this.$message({
                  message: '添加平台用户成功',
                  type: 'success'
                });
                that.dialogAddVisible= false;
                that.loadAppUserDatas();
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                });
              }
            });
          } else {
            return false;
          }
        })
      },
      submitEditForm () {
        var that = this;
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            editAppUser(that.editForm).then(response => {
              if (response.code == 0) {
                this.$message({
                  message: '修改平台用户成功',
                  type: 'success'
                });
                that.dialogEditVisible= false;
                that.loadAppUserDatas();
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                });
              }
            });
          } else {
            return false;
          }
        })
      },
      resetPassword(){
        var that = this;
        this.$refs.resetPasswordForm.validate((valid) => {
          if (valid) {
            resetUserPassword(that.resetPasswordForm).then(response => {
              if (response.code == 0) {
                this.$message({
                  message: '重置密码成功',
                  type: 'success'
                });
                that.dialogPasswordVisible= false;
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                });
              }
            });
          } else {
            return false;
          }
        })
      },
      //分页
      handleSizeChange(val) {
        this.pageable.pageSize = val;
        this.loadAppUserDatas();
      },
      handleCurrentChange(val) {
        this.pageable.currentPage = val;
        this.loadAppUserDatas();
      }
    },
    watch: {},
    created: function () {
      this.loadAppUserDatas();
      getOSSProperties(this.baseDir).then(response => {
        if(response.code == 0){
          this.ossProperties = response.data;
        }else{
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      });
    }
  };
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    float: left;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    /*font-size: 28px;*/
    color: #8c939d;
    width: 133px;
    height: 133px;
    line-height: 133px;
    text-align: center;
  }
  .avatar {
    width: 133px;
    height: 133px;
    display: block;
  }
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }

  .clearfix:after {
    clear: both
  }
</style>

